import { betterAuth } from 'better-auth';
import { username, admin } from 'better-auth/plugins';
import type { AppLoadContext } from "@remix-run/cloudflare"
import { redirect } from "@remix-run/cloudflare"
import { initDb } from './db';

export type Auth = ReturnType<typeof betterAuth>;

let auth: Auth;

export const initAuth = (env: Env) => {
  if (!auth) {
    const db = initDb(env);
    auth = betterAuth({
      database: {
        db,
        type: 'sqlite'
      },
      secondaryStorage: {
        get: key => env.KVDATA.get(`_auth:${key}`),
        set: (key, value, ttl) => {
          return env.KVDATA.put(`_auth:${key}`, value, { expirationTtl: ttl })
        },
        delete: key => env.KVDATA.delete(`_auth:${key}`),
      },
      secret: env.BETTER_AUTH_SECRET,
      // baseURL: env.BETTER_AUTH_URL,
      emailAndPassword: {
        enabled: true,
      },
      socialProviders: {
        github: {
          clientId: env.GITHUB_CLIENT_ID as string,
          clientSecret: env.GITHUB_CLIENT_SECRET as string,
        },
      },
      plugins: [username(), admin()],
    });
  }
  return auth;
};

export async function authenticate(request: Request, context: AppLoadContext, returnTo?: string) {
  const auth = initAuth(context.cloudflare.env);
  const isAuthed = await auth.api
    .getSession({
      headers: request.headers,
    })

  console.log('isAuthed:', isAuthed);

  if (isAuthed) {
    context.user = isAuthed.user;
    context.session = isAuthed.session;
    if (returnTo) {
      redirect(returnTo)
    }
  } else {
    if (returnTo) {
      redirect(returnTo)
    }
  }
}
